// 创建服务器
const http = require('http');
// 请求监听
let server = http.createServer((request, response) => {
    console.log('received');
});
// 上面的写法，可以替换为这种，基于发布订阅
server.on('request', (req, res) => {
    console.log('received2');
})
//默认端口
let port = 3000;

// 监听端口
server.listen(3000, () => {
    console.log('server start');
});

// 端口占用，启用新端口
server.on('error', (err) => {
    if (err.code == 'EADDRINUSE') {
        server.listen(++port);
    }
});

// nodemon 用来自动检测文件变化，自动重启
// nodemon xxx.js
// 安装：npm  install nodemon -g
// 使用：nodemon xxx.js




/****************实现跨域操作**************/
let server1 = http.createServer((request,response)=>{
    let client = http.request({
        port: 3000,
        hostname:'localhost',
        method:'post',
    },(res)=>{
        let arr = [];
        res.on('data',(chunk)=>{
            arr.push(chunk);
        })

        res.on('end',()=>{
            console.log(Buffer.concat(arr).toString());
            response.end(Buffer.concat(arr).toString());
        })
    })

    client.end('deliver finish')
});

server1.listen(3003,()=>{
    console.log('server start 3003');
})